package com.woniuxy.intellihome.controller.front;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.intellihome.entity.Cart;
import com.woniuxy.intellihome.entity.ResponseEntity;
import com.woniuxy.intellihome.entity.User;
import com.woniuxy.intellihome.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jobob
 * @since 2021-08-11
 */
@Controller
@RequestMapping("front/cart")
public class CartController {
    @Autowired
    private CartService cartService;

    @RequestMapping("")
    public String index(Model model){
        int userId=1;
        List<Cart> cartList = cartService.getFullCartListByUserId(userId);
        model.addAttribute("carts",cartList);
        return "shopping_cart";
    }
    @RequestMapping("homepage")
    public String homepage(){
        return "redirect:/front/SPU/index";
    }

    //页面查询购物车
    @RequestMapping("getcarts")
    @ResponseBody
    public ResponseEntity<List<Cart>> getCarts(HttpSession session){
        User user = (User) session.getAttribute("user1");
        int userId=user.getId();
        List<Cart> cartList = cartService.getFullCartListByUserId(userId);
        return new ResponseEntity<>(cartList);
    }
    //勾选数据同步(数量同步)
    @RequestMapping("checkupdate")
    @ResponseBody
    public ResponseEntity<Void> checkUpdate(@RequestBody Cart cart){
        cartService.updateById(cart);
        return ResponseEntity.SUCCESS;
    }
    //删除购物车
    @RequestMapping("delcart")
    @ResponseBody
    public ResponseEntity<Void> delCart( int id){
        cartService.removeById(id);
        return ResponseEntity.SUCCESS;
    }

    //购物车浮窗计数
    @RequestMapping("countcarts")
    @ResponseBody
    public ResponseEntity<Integer> countCart(HttpSession session) {
        User user1 = (User) session.getAttribute("user1");
        if (user1 == null) {
            return new ResponseEntity<>(0);
        }
        Cart cart =new Cart();
        cart.setUserId(user1.getId());
        Wrapper wrapper=new QueryWrapper(cart);
        List carts = cartService.list(wrapper);
        Integer countNum = carts.size();
        return new ResponseEntity<>(countNum);
    }

}

